//
// Created by sgyt on 2020/5/20.
// 使用aio_read 进行异步读操作

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <aio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <asm/errno.h>


#define BUFFER_SIZE 1024

int main(int argc,char *argv[])
{
    int fd,res;
    ssize_t readLength;
    char buffer[BUFFER_SIZE];
    struct aiocb aioread;
    //初始化
    memset(&aioread,0x00, sizeof(aioread));

    //拿到文件描述符
    fd = open("sgyt.txt",O_RDONLY);
    if(fd < 0)
    {
        perror("open function is error\n");
    }


    //设置读取
    aioread.aio_buf = malloc(BUFFER_SIZE+1);
    aioread.aio_fildes = fd;
    aioread.aio_offset = 0;
    aioread.aio_nbytes = BUFFER_SIZE;

    //开始异步读
    res = aio_read(&aioread);
    if(res < 0)
    {
        perror("aio_read is error\n");
        exit(EXIT_FAILURE);
    }

    //请求为成功时
    while(aio_error(&aioread) == EINPROGRESS)
    {
        printf("请求在等待中\n");
        sleep(1);
    }

    //获取异步读取结果
    readLength = aio_return(&aioread);
    printf("data length is [%d]\n",readLength);
    printf("data is [%s]\n",aioread.aio_buf);

    //释放缓存
    free(aioread.aio_buf);
    close(fd);
    return 0;
}